
package com.android.formula.activity;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.formula.R;
import com.android.formula.adapter.LanguageListAdapter;
import com.android.formula.adapter.TBaseAdapter;
import com.android.formula.model.Language;
import com.android.formula.task.GetLanguageDBTask;
import com.android.formula.task.IDataEventHandler;
import com.android.formula.utils.CommonUtils;
import com.android.formula.utils.Constants;
import com.android.formula.utils.PreferenceUtil;
import com.google.android.gms.ads.AdListener;

public class HomeActivity extends BaseGridViewActivity<Language> {

    private TextView mTvSelectLanguage;

    private Button mBtnNote;

    private Button mBtnAbout;

    // // Initialized to 0 and 3 only for test purposes. In real app change this
    private final static int DAYS_UNTIL_PROMPT = 1;

    private final static int LAUNCH_UNTIL_PROMPT = 3;

    private boolean isRatingShowing = false;

    private LinearLayout mButtonLayout;

    @Override
    public void initView() {
        super.initView();
        mTvSelectLanguage = (TextView) findViewById(R.id.home_txt_select_language);
        mBtnNote = (Button) findViewById(R.id.home_btn_note);
        mBtnNote.setOnClickListener(this);
        mBtnAbout = (Button) findViewById(R.id.home_btn_about);
        mBtnAbout.setOnClickListener(this);

        mButtonLayout = (LinearLayout) findViewById(R.id.home_layout_button);
        setAdListener();
    }

    @Override
    protected void clickOnPos(Language clickedItem, int pos) {
        Intent i = new Intent(this, SubjectActivity.class);
        Bundle bun = new Bundle();
        bun.putSerializable(Constants.DATA_KEY, clickedItem);
        i.putExtras(bun);
        startActivity(i);
    }

    @Override
    protected TBaseAdapter<Language> getAdapter() {
        return new LanguageListAdapter(this, mListItemDatas);
    }

    @Override
    protected void getData() {
        super.getData();
        getDialogsManager().showProgress(R.string.loading_msg);
        GetLanguageDBTask getLanguageDBTask = new GetLanguageDBTask(this,
                new IDataEventHandler<ArrayList<Language>>() {

                    @Override
                    public void onNotifyNoData() {
                        getDialogsManager().dismissProgress();
                        showNoData();
                    }

                    @Override
                    public void onNotifyErrorMessage(String title, String message) {
                        getDialogsManager().dismissProgress();
                        showNoData();
                        getDialogsManager().showErrorDialog(R.string.error_title,
                                R.string.error_msg, 0, null);
                    }

                    @Override
                    public void onNotifyData(ArrayList<Language> data) {
                        getDialogsManager().dismissProgress();
                        mListItemDatas.addAll(data);
                        if (mListItemDatas != null && mListItemDatas.size() > 0) {
                            showData();
                        } else {
                            showNoData();
                        }
                        rateAppLaunched(HomeActivity.this);
                    }
                });
        CommonUtils.executeAsyTask(getLanguageDBTask);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_home;
    }

    @Override
    protected void showNoData() {
        super.showNoData();
        mTvSelectLanguage.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void showData() {
        super.showData();
        mTvSelectLanguage.setVisibility(View.VISIBLE);
    }

    public void rateAppLaunched(Context context) {
        if (PreferenceUtil.getBoolean(context, PreferenceUtil.KEY_RATE_APP, false)) {
            return;
        }

        long launch_count = PreferenceUtil.getLong(context, PreferenceUtil.KEY_LAUNCH_COUNT, 0) + 1;
        PreferenceUtil.writeLong(context, PreferenceUtil.KEY_LAUNCH_COUNT, launch_count);

        long date_firstLaunch = PreferenceUtil.getLong(context,
                PreferenceUtil.KEY_DATE_FIRST_LAUNCH, 0);
        if (date_firstLaunch == 0) {
            date_firstLaunch = System.currentTimeMillis();
            PreferenceUtil.writeLong(context, PreferenceUtil.KEY_DATE_FIRST_LAUNCH,
                    date_firstLaunch);
        }

        if (launch_count >= LAUNCH_UNTIL_PROMPT) {

            if (System.currentTimeMillis() >= date_firstLaunch
                    + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
                showRateDialog(context);
            }
        }
    }

    private void showRateDialog(final Context context) {

        Dialog dialog = new Dialog(context);

        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        String message = "If you enjoy using "
                + context.getString(this.getApplicationInfo().labelRes)
                + ", please take a moment to rate the app. " + "Thank you for your support!";

        builder.setMessage(message)
                .setTitle("Rate " + context.getString(this.getApplicationInfo().labelRes))
                .setIcon(context.getApplicationInfo().icon).setCancelable(false)
                .setPositiveButton("Rate Now", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PreferenceUtil.writeBoolean(context, PreferenceUtil.KEY_RATE_APP, true);

                        // If your app hasn't been uploaded to market
                        // you'll get
                        // an exception.
                        // For test purposes we catch it here and show
                        // some
                        // text.
                        try {
                            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                                    .parse("market://details?id=" + getPackageName())));
                        } catch (ActivityNotFoundException e) {
                            Toast.makeText(context, "You have pressed Rate Now button",
                                    Toast.LENGTH_SHORT).show();
                        }

                        dialog.dismiss();
                    }
                }).setNeutralButton("Later", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Toast.makeText(context,
                        // "You have pressed Later button",
                        // Toast.LENGTH_SHORT)
                        // .show();
                        dialog.dismiss();
                    }
                }).setNegativeButton("Nerver", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PreferenceUtil.writeBoolean(context, PreferenceUtil.KEY_RATE_APP, true);

                        // Toast.makeText(context,
                        // "You have pressed No, Thanks button",
                        // Toast.LENGTH_SHORT).show();

                        dialog.dismiss();
                    }
                });

        dialog = builder.create();
        if (!isRatingShowing) {
            dialog.show();
            isRatingShowing = true;
        }
    }

    @Override
    public void onClickWithDelay(View v) {
        switch (v.getId()) {
            case R.id.home_btn_note:
                startActivity(new Intent(this, SubjectNoteActivity.class));
                break;
            case R.id.home_btn_about:
                startActivity(new Intent(this, AboutActivity.class));
                break;
            default:
                break;
        }
    }
    
    @SuppressWarnings("deprecation")
    @Override
    protected void setAdListener() {
        final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        
        mAdListener = new AdListener() {
            @Override
            public void onAdFailedToLoad(int errorCode) {
                super.onAdFailedToLoad(errorCode);
                mAdView.setVisibility(View.GONE);
                params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
                mButtonLayout.setLayoutParams(params);
            }
            
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                mAdView.setVisibility(View.VISIBLE);
                params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0);
                params.addRule(RelativeLayout.ABOVE, R.id.home_layout_ads);
                mButtonLayout.setLayoutParams(params);
            }
        };
    }
}
